const fs = require('fs');
// 1. 回调地狱模式
// callback hell
fs.readFile('./mock/file1.json', (err, data) => {
  const file2Path = JSON.parse(data.toString()).name

  fs.readFile(file2Path, (err, res) => {
    const file3Path = JSON.parse(res.toString()).name

    fs.readFile(file3Path, (err, file3) => {
      const file4Path = JSON.parse(file3.toString()).name

    })
  })
})



// async await 后面跟一个promise
function readFile(url) {
  return new Promise((resolve, reject) => {
    fs.readFile(url, (err, data) => {
      if (err) {
        reject(err)
        return
      }
      resolve(JSON.parse(data))
    })
  })
}

readFile('./mock/file1.json')
  .then(res => {
    return readFile(res.name)
  })
  .then(res => {
    return readFile(res.name)
  })
  .then(res => {
    console.log(res, 'res')
  })

  
// 异步解决终极方案；
// 将异步代码以同步的方式输出出来；
async function myReadFile() {
  const  data = await readFile('./mock/file1.json')
  const  data2 = await readFile(data.name)
  const  data3 = await readFile(data2.name)
  console.log(data3, 'data')
  return data3;
}


/*
  1.  await 后面跟promise
  2. await必须在async里面
  3. async 执行返回也是一个promise
  4. try-catch 捕捉错误
*/ 


// console.log(myReadFile())
